using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb;
using Nsb.Classes;
using ThemeChain;
using jQueryApi;

namespace Yoshi.Classes
{
    [IgnoreNamespace]
    public class GodMode : Ask
    {
        public void AwEv(Await awp, jQueryEvent e)
        {
            CancelEvent(e);
            bool gm = (bool) Storage.GetLocal("GodMode");
            Storage.SetLocal("GodMode", !gm);
            ThemeBase.GodMode = !gm;

            OkAw(awp,
                 new Dictionary(
                     "Msg", String.Format("Turning God mode \"<span style='color:#009'>{0}</span>\"", gm ? "off" : "on"),
                     "Customize", (Action) CustomStuff
                     )
                );
        }

        public void CustomStuff()
        {
            List<ErrorLogItem> log = (List<ErrorLogItem>) Storage.GetLocal("ErrorLog");

            if (Script.IsValue(log))
            {
                jQuery.FromHtml("<button/>")
                    .AppendTo(jQuery.Select(".Content", Element))
                    .Html("Obliviate log")
                    .Click(delegate
                           {
                               Storage.RemoveLocal("ErrorLog");
                               FlashWindow();
                           })
                    ;

                string ot = "";

                foreach (ErrorLogItem i in log)
                {
                    Type.SetField(i, "time", new Date(i.time).Format("ddd yyyy-MM-dd hh:mm:ss:fff"));
                    ot += Rx.PrettyJson(i).ReplaceRegex((RegularExpression) Script.Literal(@"/^{\s*|\s*}$/g"), "") + "\n\n";
                }

                jQuery.FromHtml("<div class='Log'/>")
                    .AppendTo(jQuery.Select(".Content", Element))
                    .Html(Transform.Htmlize(ot))
                    .Hide()
                    ;

                jQuery.FromHtml("<span class='Shower' style='cursor:pointer'/>")
                    .AppendTo(jQuery.Select(".Content", Element))
                    .Html("show log")
                    .Click(
                        delegate
                        {
                            jQuery.Select(".Shower", Element).Remove();
                            jQuery.Select(".Log", Element).SlideDown();
                        })
                    ;
            }
        }
    }

    public abstract class ErrorLogItem
    {
        public int line;
        public string msg;
        public int time;
        public string url;
    }
}